<template>
	<view>
		<cu-custom :key="'header'+headerKey" bgColor="bg-blue-light" :isBack="true" backText="返回" title="培训签到"></cu-custom>
		<view class="bg-blue-light" style="min-height: 60rpx;">
			<view class="flex justify-start align-center" style="line-height: 32rpx;padding-left: 30rpx;">
				<view class="bg-white text-center text-blue" style="border-radius: 10rpx 0 10rpx 0;width: 80rpx; margin-right: 30rpx;">
					课程
				</view>
				<view class="text-lg text-bold " style="width: 550rpx;">
					{{fromData.curriculumName?fromData.curriculumName:'您没有培训课程'}}
				</view>
			</view>
		</view>
		<zh-text labelAlign="left" label="上课时间" labelWidth="150rpx" :value="fromData.trainDateText" ></zh-text>
		<zh-text labelAlign="left" label="上课地点" labelWidth="150rpx" :value="fromData.address?fromData.address:''+fromData.addressDetail?fromData.addressDetail:''" ></zh-text>
		<zh-text labelAlign="left" label="定位地点" labelWidth="150rpx" :value="curLocation"   :rightIconClass="locationError?'basefont icon-reload text-red':'basefont icon-reload text-blue'" @right-icon-click="refresh" ></zh-text>
		<zh-input type="textarea" labelAlign="left" label="备注" labelWidth="100rpx" v-model="remarks"  placeholder="签到备注信息"  ></zh-input>
		<view class="bg-white" >
			<view  class="bg-white" style="padding: 20rpx 30rpx;">
				<view class="flex justify-between align-center">
					<view class="basefont icon-radio-fill text-blue">
						上课时间：<text>{{fromData.begTimeText}}</text>
					</view>
					<view v-if="fromData.signInMsg" class='cu-tag round':class="fromData.signInFlag?'bg-green':'bg-red'">
						<text>{{fromData.signInMsg?fromData.signInMsg:''}}</text><text v-if="fromData.signInTimeText">({{fromData.signInTimeText}})</text>
					</view>
				</view>
				<view style="height: 320rpx;border-left: 2rpx solid #0081ff !important;margin-left: 12rpx;">
				</view>
				<view class="flex justify-between align-center">
					<view class="basefont icon-radio-fill text-orange">
						下课时间：<text>{{fromData.endTimeText}}</text>
					</view>
					<view v-if="fromData.signOutMsg" class='cu-tag round' :class="fromData.signOutFlag?'bg-green':'bg-red'">
						<text>{{fromData.signOutMsg?fromData.signOutMsg:''}}</text><text v-if="fromData.signOutTimeText">({{fromData.signOutTimeText}})</text>
					</view>
				</view>
			</view>
			<view class="text-center " style="margin-top: -390rpx;">
				<button class="cu-btn round  shadow margin-tb-sm" @tap="signIn" :class="signInBg">
					<view>
					<view style="font-size: 36rpx;">{{text}}</view>
					<view style="font-size: 28rpx;">{{currentTime.substr(0,12)}}</view>
					<view style="font-size: 28rpx;">{{currentTime.substr(12)}}</view>
					</view>
				</button>
			</view>
		</view>
		<view style="width: 100% ;height: 16.4em;margin-top: 60rpx;">
			<!--#ifdef MP-WEIXIN -->
			<map id="navi_map" :longitude="longitude" :latitude="latitude" :circles="circles"  scale="15" :markers="markers" style="width: 100%;height: 100%;" ></map>
			<!--#endif -->
			<!--#ifdef H5 -->
			<Amap ref="mapView" mapHeight="16.4em" :lat="mapConfig.latitude" :lng="mapConfig.longitude" :errorRange="mapConfig.errorRange" :infoContent="mapConfig.infoContent" @change="mapChange"></Amap>
			<!--#endif -->
		</view>
		<view class="cu-form-group" style="justify-content:center">
			<view class="text-gray text-sm text-center bg-white" @tap="refresh">
				刷新当前位置<text style="padding-left: 10rpx;" class="basefont icon-reload"></text>
			</view>
		</view>
		<u-modal v-model="modelShow"  :content="modelContent" confirm-color="#0081ff" @confirm="modelConfirm"></u-modal>
		<u-toast ref="uToast" />
	</view>
</template>
<script>
	import store from '@/store';
	// #ifdef MP-WEIXIN
	import amap from '@/common/amap-wx.js';
	// #endif
	// #ifdef H5
	import Amap from '@/pages/system/map/h5LocationMap.vue'
	// #endif
	import systemConfig from '@/common/config/systemConfig.js'
	import miment from 'miment'
	import api from '@/api/society/train/trainSignIn.js'
	import util from '@/common/util/util.js'
	export default {
		onShow() {
			this.headerKey += 1;
		},
		components: {
			// #ifdef H5
			Amap
			// #endif
		},
		data() {
			return {
				headerKey:0,
				fromData:{},
				trainDate:null,
				curLocation:"定位中",
				locationError:false,
				markers: [],
				circles: [],
				latitude:null,
				longitude:null,
				locationData:{},
				amapPlugin: null,
				modelType:'',
				modelShow:false,
				modelContent:'功能目前在测试中，尚未开放',
				timer: '', //定义一个定时器的变量
				canSave:false,
				canSignIn:false,
				signInBg:'bg-gradual-blue-light',
				text:'签到',
				remarks:'',
				currentTime: miment().format('YYYY年MM月DD日 hh:mm:ss'), // 获取当前时间
				signInTime:'',
				trainMarker:null,
				type:'signIn',
				trainCurriculumId:null,
				mapConfig:{}
			}
		},
		onLoad: function (option) {
			// #ifdef MP-WEIXIN
			this.amapPlugin = new amap.AMapWX({
				key: systemConfig.amapKey
			});
			// #endif
			var vm = this;
			vm.timer = setInterval(() => {
				vm.currentTime = miment().format('YYYY年MM月DD日 hh:mm:ss');
			}, 1000);
			//获取培训信息
			
			if (this.$Route.query) {
				this.trainCurriculumId=this.$Route.query.trainCurriculumId;
			}
			this.getDetail()
		},
		onReady() {
			// #ifdef MP-WEIXIN
			this.isGetLocation()
			// #endif
		},
		methods: {
			modelConfirm(){
				
			},
			getDetail(){
				const data ={}
				data.trainCurriculumId=this.trainCurriculumId
				console.log(data)
				this.$http.post(api.getDetailByUser, data).then(res => {
					console.log(res.result)
					this.fromData= res.result
					this.trainCurriculumId=res.result.trainCurriculumId
					// #ifdef MP-WEIXIN
					if(res.result.latitude&&res.result.longitude){
						const circle={}
						circle.latitude=res.result.latitude
						circle.longitude=res.result.longitude
						circle.radius=res.result.errorRange?res.result.errorRange:50
						circle.strokeWidth=1
						circle.fillColor='#0081ff'
						circle.strokeColor="#FFFFFF"
						circle.strokeOpacity=0.4
						this.circles.push(circle)
						const  marker={}
						marker.id =1
						marker.latitude=res.result.latitude
						marker.longitude=res.result.longitude
						marker.width=23
						marker.height=33
						 //自定义标记点上方的气泡窗口
						marker.callout={
						    padding:2,        //callout 文本边缘留白
						    fontSize:15,      //callout  文字大小
						    bgColor:'#FFFFFF',   //callout 背景颜色
						    color:'#e54d42',  //callout 文字颜色
						    borderRadius:5,   //边框圆角
						    display:'BYCLICK',//callout 'BYCLICK':点击显示; 'ALWAYS':常显
						    content:'培训地点' //地理位置名称
						}
						this.trainMarker = marker
						this.markers.push(marker)
					}
					// #endif
					// #ifdef H5
					const mapConfig ={}
					mapConfig.errorRange =res.result.errorRange?res.result.errorRange:50
					mapConfig.latitude=res.result.latitude
					mapConfig.longitude=res.result.longitude
					mapConfig.infoContent = "培训地点"
					this.mapConfig=mapConfig
					// #endif
					const personStatus=res.result.personStatus
					const status=res.result.status
					if(personStatus=='not_start'){
						this.text = "未开始"
						this.modelContent="培训尚未开始"
						this.canSignIn=false
						this.signInBg="bg-gray"
					}else if(personStatus=='sign_in'){
						this.text = "签到"
						this.canSignIn=true
						this.signInBg="bg-gradual-blue-light"
						this.type="signIn"
					}else if(personStatus=='wait'){
						this.text = "等待上课"
						this.canSignIn=false
						this.modelContent="已签到，请耐心等待上课"
						this.signInBg="bg-gradual-green"
					}else if(status=='ing'&&personStatus=='not_sign_in'){
						this.text = "签到"
						this.canSignIn=true
						this.signInBg="bg-gradual-orange"
						this.type="signIn"
					}else if(personStatus=='sign_out'){
						this.text = "签退"
						this.canSignIn=true
						this.signInBg="bg-gradual-blue-light"
						this.type="signOut"
					}else if(res.result.ingSignFlag=='1'&&status=='ing'&&!res.result.signOutTime){
						this.text = "签退"
						this.canSignIn=true
						this.signInBg="bg-gradual-orange"
						this.type="signOut"
					}else if(status=='ing'&&res.result.signOutTime){
						this.text = "早退"
						this.canSignIn=false
						this.modelContent="您已早退"
						this.signInBg="bg-gradual-red"
					}else{
						this.modelContent="培训已结束"
						this.text = "已结束"
						this.canSignIn=false
						this.signInBg="bg-gray"
					}
				}).catch(error => {	
					this.text = "查询失败"
					this.modelContent="查询课程信息失败,请返回重新进入签到页面"
					this.canSignIn=false
					this.signInBg="bg-gray"
					this.trainMarker =null
				})
			},
			signIn(){
				if(this.canSignIn){
					if(!this.latitude||!this.longitude){
						this.$refs.uToast.show({
							title: "定位失败，请刷新",
							// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
							type: 'error', 
							position:'top',
							// 如果不需要图标，请设置为false
							icon: true,
							duration:3000
						})
						return
					}
					if(!this.fromData.latitude||!this.fromData.longitude){
						this.$refs.uToast.show({
							title: "培训地址设置无效，请联系系统管理员",
							// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
							type: 'error', 
							position:'top',
							// 如果不需要图标，请设置为false
							icon: true,
							duration:3000
						})
						return
					}
								
					let dis = util.distance(this.latitude, this.longitude,this.fromData.latitude,this.fromData.longitude)
					const errorRange =this.fromData.errorRange?this.fromData.errorRange:50
					if(errorRange<dis){
						this.$refs.uToast.show({
							title: "您当前所在位置，不在签到范围",
							// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
							type: 'error', 
							position:'top',
							// 如果不需要图标，请设置为false
							icon: true,
							duration:3000
						})
						return
					}
					const vm = this;
					const data={}
					data.locationAddress=this.curLocation
					data.latitude=this.latitude
					data.longitude=this.longitude
					data.targetLatitude = this.fromData.latitude
					data.targetLongitude = this.fromData.longitude
					data.remarks = this.remarks
					data.distance=dis
					data.errorRange=errorRange
					data.signInRules='3'
					data.signInType='train'
					data.objectId=this.fromData.trainCurriculumId
					if(this.type=='signIn'){
						data.begTime=this.fromData.leadTime
						data.endTime=this.fromData.begTime
					}else{
						data.begTime=this.fromData.endTime
						data.endTime=this.fromData.delayTime
					}
					const regeocodeData = this.locationData.regeocodeData
					const addressComponent =regeocodeData.addressComponent
					console.log(addressComponent)
					if(addressComponent){
						data.provinceCode=''
						data.provinceValue=addressComponent.province
						data.cityCode=''
						data.cityValue=addressComponent.city
						data.countyCode = addressComponent.adcode
						data.countyValue = addressComponent.district
						data.townCode = addressComponent.towncode
						data.townValue =addressComponent.township
					}
					this.$http.post(api.addSignIn, data).then(res => {
						this.$refs.uToast.show({
							title: '签到成功',
							// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
							type: 'success', 
							position:'top',
							// 如果不需要图标，请设置为false
							icon: true,
							duration:4000
						})
						this.getDetail()
					}).catch(error => {	
						
					})
					
				}else{
					this.$refs.uToast.show({
						title: this.modelContent,
						// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
						type: 'error', 
						position:'top',
						// 如果不需要图标，请设置为false
						icon: true,
						duration:3000
					})
				}
			},
			refresh(){
				// #ifdef MP-WEIXIN
				this.isGetLocation()
				// #endif
				// #ifdef H5
				this.$refs.mapView.h5Geolocation()
				// #endif
			},
			// #ifdef H5
			mapChange(data){
				this.locationData = data
				if(data&&data.latitude&&data.longitude&&data.regeocodeData.formatted_address){
					this.curLocation = data.regeocodeData.formatted_address
					this.latitude=data.latitude
					this.longitude=data.longitude
				}else{
					this.curLocation = '定位失败'
					this.latitude=null
					this.longitude=null
				}
				console.log(data)
			},
			// #endif
			// #ifdef MP-WEIXIN
			getRegeo(){
				const that = this;
				this.markers=[]
				this.amapPlugin.getRegeo({
					success: (data) => {
						if(data){
							this.locationData = data[0]
							const regeocodeData=data[0].regeocodeData
							if(regeocodeData){
								this.curLocation = regeocodeData.formatted_address
								this.latitude=data[0].latitude
								this.longitude=data[0].longitude
								const  marker={}
								marker.id =0
								marker.latitude=data[0].latitude
								marker.longitude=data[0].longitude
								marker.width=23
								marker.height=33
								 //自定义标记点上方的气泡窗口
								marker.callout={
								    padding:2,        //callout 文本边缘留白
								    fontSize:15,      //callout  文字大小
								    bgColor:'#FFFFFF',   //callout 背景颜色
								    color:'#0081ff',  //callout 文字颜色
								    borderRadius:5,   //边框圆角
								    display:'BYCLICK',//callout 'BYCLICK':点击显示; 'ALWAYS':常显
								    content:'我的位置' //地理位置名称
								}
								this.markers.push(marker)
								if(this.trainMarker){
									this.markers.push(this.trainMarker)
								}
							}
						}
					},
					fail:(info)=> {
						this.curLocation='定位失败'
						this.latitude=null
						this.longitude=null
					}
				});
				
			},
			isGetLocation(a="scope.userLocation"){ // 3. 检查当前是否已经授权访问scope属性，参考下截图
				var _this=this;
				uni.getSetting({
					success(res) {	
						const authFlag=res.authSetting[a]
						if (!authFlag) {  //3.1 每次进入程序判断当前是否获得授权，如果没有就去获得授权，如果获得授权，就直接获取当前地理位置
							if(authFlag==null||authFlag==undefined){
								_this.getRegeo(this)
							}else{
								wx.showModal({
								    title: '提示',
								    content: '需要获取您的位置信息，用于签到',
								    cancelText:'不授权',
								    cancelColor:'#999',
								    confirmText:'授权',
								    confirmColor:'#0081ff',
								    success(res) {
								        if (res.confirm) {
								            uni.openSetting({
								                success(res) {
													_this.getRegeo(this);
								                },
												fail(res) {
													_this.$Router.back(1)
												}
								            })                                
								        } else if (res.cancel) {
								            _this.getRegeo(this)
								        }
								    }
								})
							}
						}else{
							_this.getRegeo(this)
						}
					}
				});
			}
			// #endif
		},
		beforeDestroy() {
			if (this.timer) {
				clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
			}
		}
		
	}
</script>

<style>
	.cu-btn {
		display: inline-flex;
		text-align: center;
		justify-content: center;
		align-items: center;
		width: 288rpx;
		height: 288rpx;
	}
	
</style>
